<?php

namespace app\controller;

use app\BaseController;
use app\model\MaterialCategoryModel;
use think\facade\Db;
use think\facade\Request;

class CangkuWuliao extends BaseController
{
    /**
     * 获取库位列表
     */
    public function getShelfList()
    {
        try {
            $list = Db::name('shelf')
                ->field('id, shelf_code as label')
                ->select()
                ->toArray();

            return json([
                'code' => 200,
                'msg' => '获取库位列表成功',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取库位列表失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取物料列表
     */
    public function getList()
    {
        try {
            $page = Request::param('page', 1);
            $pageSize = Request::param('pageSize', 20);
            $title = Request::param('title', '');
            $shelfId = Request::param('shelfId', 0);
            $category_id = Request::param('category_id', 0);

            $where = [];
            if (!empty($title)) {
                $where[] = ['m.material_name', 'like', "%{$title}%"];
            }

            if (!empty($shelfId)) {
                $where[] = ['m.shelf_id', '=', $shelfId];
            }
            if (!empty($category_id)) {
                $where[] = ['m.category_id', '=', $category_id];
            }

            $user = getUserInfo();
            $dataRole = dataPermissionCheck($user);
            if (in_array($dataRole, ['user', 'company'])) {
                $where[] = ['m.company_id', '=', $user['company_id']];
            }


            $count = Db::name('material_category')
                ->alias('m')
                ->where($where)
                ->count();

            $list = Db::name('material_category')
                ->alias('m')
                ->join('shelf s', 'm.shelf_id = s.id', 'left')
                ->join('category c', 'm.category_id = c.id', 'left')
                ->field('m.*, s.shelf_code as shelf_name, c.name as category_name')
                ->where($where)
                ->page($page, $pageSize)
                ->order('m.id', 'desc')
                ->select()
                ->toArray();

            return json([
                'code' => 200,
                'msg' => '获取物料列表成功',
                'data' => [
                    'list' => $list,
                    'total' => $count
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取物料列表失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 编辑/添加物料
     */
    public function editMaterial()
    {
        try {
            $data = Request::post();

            // 验证必填字段
            if (empty($data['material_name'])) {
                return json(['code' => 400, 'msg' => '物料名称不能为空']);
            }

            if (empty($data['material_code'])) {
                return json(['code' => 400, 'msg' => '物料编码不能为空']);
            }

            if (empty($data['shelf_id'])) {
                return json(['code' => 400, 'msg' => '库位不能为空']);
            }

            // 检查库位是否存在
            $shelfExists = Db::name('shelf')->where('id', $data['shelf_id'])->find();
            if (!$shelfExists) {
                return json(['code' => 400, 'msg' => '所选库位不存在']);
            }

            // 检查物料名称是否重复
            $nameExists = Db::name('material_category')
                ->where('material_name', $data['material_name'])
                ->where('id', '<>', $data['id'] ?? 0)
                ->find();

            if ($nameExists) {
                return json(['code' => 400, 'msg' => '物料名称已存在']);
            }

            // 检查物料编码是否重复
            $codeExists = Db::name('material_category')
                ->where('material_code', $data['material_code'])
                ->where('id', '<>', $data['id'] ?? 0)
                ->find();

            if ($codeExists) {
                return json(['code' => 400, 'msg' => '物料编码已存在']);
            }

            if (!empty($data['max_quantity']) && !empty($data['warning_quantity'])) {
                if ($data['max_quantity'] <= $data['warning_quantity']) {
                    return json(['code' => 400, 'msg' => '最大与购买库存数量不能小于等于预警数量']);
                }

            }

            $user = getUserInfo();
            // 准备更新或插入的数据
            $saveData = [
                'material_name' => $data['material_name'],
                'material_code' => $data['material_code'],
                'shelf_id' => $data['shelf_id'],
                'warning_quantity' => $data['warning_quantity'] ?? 0,
                'max_quantity' => $data['max_quantity'] ?? 0,
                'material_type' => $data['material_type'] ?? '标准件',
                'last_update_time' => date('Y-m-d H:i:s'),
                'company_id' => $user['company_id'],
                'alias_name' => $data['alias_name'],
                'spec' => $data['spec'],
                'unit' => $data['unit'],
                'status' => $data['status'],
                'category_id' => $data['category_id'],
                'cost_price' => $data['cost_price'] ?? 0,
            ];

            // 更新或插入
            if (!empty($data['id'])) {
                // 更新时不修改current_quantity字段
                Db::name('material_category')
                    ->where('id', $data['id'])
                    ->update($saveData);

                return json([
                    'code' => 200,
                    'msg' => '更新物料成功',
                    'data' => $data['id']
                ]);
            } else {
                // 新增时设置current_quantity为0
                $saveData['current_quantity'] = 0;

                $id = Db::name('material_category')->insertGetId($saveData);

                if (!empty($data['current_quantity']) && $data['current_quantity'] > 0) {
                    $saveData = [];
                    $saveData['current_quantity'] = $data['current_quantity'];
                    if ($saveData['current_quantity'] > 0) {
                        (new MaterialCategoryModel())->stockInOut($id, $saveData['current_quantity'], '首次添加物料',
                            0);
                    }
                    Db::name('material_category')->where('id', $id)->update($saveData);
                }
                return json([
                    'code' => 200,
                    'msg' => '添加物料成功',
                    'data' => $id
                ]);
            }
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '操作失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 生成唯一的物料编码
     */
    public function generateMaterialCode()
    {
        try {
            // 生成随机编码 (8位字母和数字的随机混合)
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            $isUnique = false;
            $code = '';

            // 尝试最多10次生成唯一编码
            for ($attempt = 0; $attempt < 10; $attempt++) {
                $code = '';

                // 生成8位随机字符（字母和数字混合）
                for ($i = 0; $i < 8; $i++) {
                    $code .= $chars[mt_rand(0, strlen($chars) - 1)];
                }

                // 确保至少包含一个字母和一个数字
                if (!preg_match('/[A-Z]/', $code) || !preg_match('/[0-9]/', $code)) {
                    continue; // 重新生成
                }

                // 检查编码是否已存在
                $exists = Db::name('material_category')
                    ->where('material_code', $code)
                    ->find();

                if (!$exists) {
                    $isUnique = true;
                    break;
                }
            }

            if (!$isUnique) {
                return json([
                    'code' => 500,
                    'msg' => '无法生成唯一的物料编码，请稍后重试'
                ]);
            }

            return json([
                'code' => 200,
                'msg' => '生成物料编码成功',
                'data' => $code
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '生成物料编码失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 删除物料
     */
    public function deleteMaterial()
    {
        try {
            $ids = Request::post('ids');

            if (empty($ids)) {
                return json([
                    'code' => 400,
                    'msg' => '请选择要删除的物料'
                ]);
            }

            // 将逗号分隔的ID转换为数组
            $idArray = explode(',', $ids);

            // 删除物料
            $count = Db::name('material_category')->whereIn('id', $idArray)->delete();

            if ($count > 0) {
                return json([
                    'code' => 200,
                    'msg' => '删除成功',
                    'data' => $count
                ]);
            } else {
                return json([
                    'code' => 400,
                    'msg' => '删除失败，物料不存在或已被删除'
                ]);
            }
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '删除失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取单个物料详情
     */
    public function getMaterialById()
    {
        try {
            $id = Request::param('id', 0);

            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '物料ID不能为空'
                ]);
            }

            $material = Db::name('material_category')
                ->alias('m')
                ->join('shelf s', 'm.shelf_id = s.id')
                ->field('m.*, s.shelf_code as shelf_name')
                ->where('m.id', $id)
                ->find();

            if (!$material) {
                return json([
                    'code' => 404,
                    'msg' => '物料不存在'
                ]);
            }

            return json([
                'code' => 200,
                'msg' => '获取物料详情成功',
                'data' => $material
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取物料详情失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取物料下拉列表
     */
    public function getSelectList()
    {
        // 查询所有可用的物料
        $list = Db::name('material_category')
            ->field('id, material_name, material_code, "个" as unit, current_quantity as stock_quantity')
            ->order('id', 'desc')
            ->select()
            ->toArray();

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $list
        ]);
    }

    /**
     * 获取物料详情（包括库存信息）
     */
    public function getMaterialDetail()
    {
        $id = input('id', 0, 'intval');

        if ($id <= 0) {
            return json([
                'code' => 400,
                'msg' => '参数错误',
                'data' => null
            ]);
        }

        // 查询物料详情
        $info = Db::name('material_category')
            ->field('id, material_name, material_code, "个" as unit, current_quantity as stock_quantity')
            ->where('id', $id)
            ->find();

        if (!$info) {
            return json([
                'code' => 400,
                'msg' => '物料不存在',
                'data' => null
            ]);
        }

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $info
        ]);
    }
} 